'''
play_url:
https://m701.music.126.net/20220421175147/a34676569f1ffd600b7abd47ca1a0d06/jdyyaac/obj/
w5rDlsOJwrLDjj7CmsOj/13500559533/d967/8b9c/dbe0/13b351a855c7177fe1594fa4bca2e96d.m4a

get_play_url:https://music.163.com/weapi/song/enhance/player/url/v1?csrf_token=
'''
'''
1. 爬取网易云歌曲并下载转化为mp3
'''

import requests
url = 'https://music.163.com/weapi/song/enhance/player/url/v1?csrf_token='
heards = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.88 Safari/537.36"
}

from Cryptodome.Cipher import AES
from base64 import b64encode
import json

b = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
a = 16
data = {
    "csrf_token": "",
    "encodeType": "aac",
    "ids": "[1384026889]",
    "level": "standard"
}
e = '010001'
f = '00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7'
g = '0CoJUm6Qyw8W8jud'
i = "3Ri8FyqQ2SrcHarT"

def getencSecKey():
    return "142c342d7f1e13c94746877a9ddc15e3fcef88608b667d4a04fe6a98948c88bbca1b6f4396430f00f94b627181172e074b6be56880f733e145a27a2687460efe47acb0966c67f9d3db0142ab80f315d4520d72959af3a3b1959c3e864288e6b6e1753da9cff2d4c122faca8bf2695b5f926a63db95c60a605c59b287a0434a7d"

def to_16(data):
    pad = 16 - len(data) % 16
    data += chr(pad) * pad
    return data

def get_params(data):
    first = enc_params(data, g)
    second = enc_params(first, i)
    return second

def enc_params(data, key):
    data = to_16(data)
    aes = AES.new(key=key.encode("utf-8"), IV="0102030405060708".encode("utf-8"), mode=AES.MODE_CBC)
    bs = aes.encrypt(data.encode("utf-8"))
    return str(b64encode(bs), "utf-8")

resp = requests.post(url=url, headers=heards, data={
    "params": get_params(json.dumps(data)),
    "encSecKey": getencSecKey()
})
music_url = resp.json()['data'][0]['url']
music_resp = requests.get(url=music_url, headers=heards)
with open('./文件/所念皆星河.m4a', mode='wb') as f:
    f.write(music_resp.content)

import os
m4a_path = "D:/pycharm/pythonProject/爬虫/文件/所念皆星河.m4a" #m4a文件所在文件夹
print(m4a_path[:-6])
# m4a_file = os.listdir(m4a_path)
# for i, m4a in enumerate(m4a_file):
os.system("D:/ffmpeg/ffmpeg-5.0.1-essentials_build/bin/ffmpeg -i "+ m4a_path + " " + m4a_path[:-5] + str("所念皆星河") + ".mp3" )